import FormItem from "antd/es/form/FormItem";
import {Button, DatePicker, Form, Input, Select, Space, Table} from "antd";
import React, {useCallback, useEffect, useMemo, useState} from "react";
import {observer} from "mobx-react-lite";
import {CreateMarketAccountRequest, MarketAccountResponse, updateMarketAccount} from "../apis/MarketAccountApi";
import {
    createMarketSaleDocument,
    MarketSaleDocumentStatus, marketSaleDocumentStatusMap,
    QueryMarketSaleDocumentResponse, QueryMarketSaleDocumentResponseInMarketAccount,
    queryMarketSaleDocumentsByMarketAccountId
} from "../apis/MarketSaleDocumentApi";
import FormDrawer from "./FormDrawer";
import DataPageLayout from "./DataPageLayout";
import employeeAuthorizationStore from "../store/EmployeeAuthorizationStore";
import {EditOutlined} from "@ant-design/icons";
import GoodsTable from "./GoodsTable";
import {castFilterValue, mergePaginationAndPageable, useTableFilterDateRangeColumnProps} from "../utils/AntdTableUtils";
import {QueryMarketOrderResponse} from "../apis/MarketOrderApi";
import {LocalDate, OffsetDateTime} from "@js-joda/core";
import LoadableButton from "./LoadableButton";
import {Dayjs} from "dayjs";
import {Pageable} from "../utils/Page";
import {queryDirectSaleClients} from "../apis/DirectSaleClientApi";
import {useNavigate} from "react-router-dom";
import {useGlobalStyle} from "../global.style";
import {YEAR_MONTH_DAY_FORMATER} from "../utils/Date";

export function buildEditMarketAccountFormItems() {
    return <>
        <FormItem label={"名称"} name={"name"} required>
            <Input/>
        </FormItem>
    </>
}

const MarketAccountTabItemPage = (({marketId, data, onChange}: {
    data: MarketAccountResponse,
    marketId: number,
    onChange: (data: MarketAccountResponse) => void,
}) => {
    const [openUpdateMarketAccountDrawer, setOpenUpdateMarketAccountDrawer] = useState(false)
    const [loading, setLoading] = useState(false)
    const [documents, setDocuments] = useState<QueryMarketSaleDocumentResponseInMarketAccount[]>([])
    const [totalElements, setTotalElements] = useState(0)
    const [pageable, setPageable] = useState<Pageable>(new Pageable())
    let query = useCallback(() => {
        setLoading(true)
        queryMarketSaleDocumentsByMarketAccountId(data.id,pageable).then(res => {
            setDocuments(res.data.content)
            setTotalElements(res.data.totalElements)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), data.id]);
    useEffect(() => {
        query()
    }, [query]);

    function buildFormItems() {
        return <>
            <Form.Item label={"备注"} name={"note"}>
                <Input.TextArea/>
            </Form.Item>
            <Form.Item label={"时间范围"} name={"yearAndMonth"} rules={[{required: true,}]}>
                <DatePicker.MonthPicker/>
            </Form.Item>
        </>
    }

    let globalStyle = useGlobalStyle();

    const [openUpdateMarketAccountSaleDocumentDrawer, setOpenUpdateMarketAccountSaleDocumentDrawer] = useState(false)

    const [openAddMarketAccountSaleDocumentDrawer, setOpenAddMarketAccountSaleDocumentDrawer] = useState(false)
    // const [editingDocumentId, setEditingDocumentId] = useState<number>()
    // const editingDocument = useMemo(() => {
    //     if(!editingDocumentId){
    //         return undefined
    //     }else {
    //         let document = documents.find(it=>it.id === editingDocumentId);
    //         return {
    //
    //         }
    //     }
    // }, [editingDocumentId]);
    let navigate = useNavigate();
    return (<>
        <FormDrawer<CreateMarketAccountRequest> open={openUpdateMarketAccountDrawer} title={"修改户头"}
                                                initialValues={{name:data.name,}}
                                                onClose={() => setOpenUpdateMarketAccountDrawer(false)}
                                                onConfirm={async values => {
                                                    let response = await updateMarketAccount(marketId, data.id, values);
                                                    onChange({id: data.id, name: values.name})
                                                    setOpenUpdateMarketAccountDrawer(false)
                                                }}>
            {buildEditMarketAccountFormItems()}
        </FormDrawer>

        <FormDrawer<EditMarketAccountSaleDocumentRequest> open={openAddMarketAccountSaleDocumentDrawer}
                                                          title={"新增销售记录"} onClose={() => {
            setOpenAddMarketAccountSaleDocumentDrawer(false)
        }} onConfirm={async values => {
            //@ts-ignore
            const yearAndMonth = values.yearAndMonth
            await createMarketSaleDocument(data.id, {
                note: values.note,
                year: yearAndMonth.year(),
                month: yearAndMonth.month()+1,
            });
            setOpenAddMarketAccountSaleDocumentDrawer(false)
            query()
        }}>
            {buildFormItems()}
        </FormDrawer>

        <FormDrawer open={openUpdateMarketAccountSaleDocumentDrawer} title={"修改销售记录"} onClose={() => {
            setOpenUpdateMarketAccountSaleDocumentDrawer(false)
        }} onConfirm={async (values) => {

        }}>
            {buildFormItems()}
        </FormDrawer>

        <DataPageLayout leftActions={<>
            {employeeAuthorizationStore.hasAuthority("卖场_户头_修改") && <Button onClick={() => {
                setOpenUpdateMarketAccountDrawer(true)
            }}><EditOutlined/>修改户头</Button>}
        </>
        } rightActions={
            <>
                <Button type={"primary"} onClick={() => {
                    setOpenAddMarketAccountSaleDocumentDrawer(true)
                }}>新增销售记录</Button>
            </>
        }>
            <Table<QueryMarketSaleDocumentResponseInMarketAccount> pagination={{pageSize:pageable.size,total:totalElements,current:pageable.page,}} onRow={record => {
                return {
                    onClick() {
                        navigate(`/markets/${marketId}/saleDocuments/${record.year}/${record.month}?accountId=${data.id}`)
                    }
                }
            }} className={globalStyle.rowClickableTable} size={"small"}
                                                                   onChange={(pagination, filters, sorter) => {
                                                                       setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                                                                   }}
                                                                   columns={[
                                                                       {
                                                                           title: "月份",
                                                                           dataIndex: "yearAndMonth",
                                                                           render: (_, record, index) => {
                                                                               return `${record.year}-${record.month}`
                                                                           },
                                                                           sorter:true,
                                                                       }, {
                                                                           title: "状态",
                                                                           dataIndex: "status",
                                                                           render: (value: MarketSaleDocumentStatus) => {
                                                                               return marketSaleDocumentStatusMap[value]
                                                                           }
                                                                       }, {
                                                                           title: "创建时间",
                                                                           dataIndex: "createdDateTime",
                                                                           render: (value) => value.format(YEAR_MONTH_DAY_FORMATER),
                                                                           sorter:true,
                                                                       },
                                                                       {
                                                                           title: "单品数量",
                                                                           dataIndex: "goodsKindAmount",
                                                                       },
                                                                       {
                                                                           title: "操作",
                                                                           render: (_, item) => {
                                                                               return <Space>
                                                                                   {employeeAuthorizationStore.hasAuthority("卖场_户头_修改") &&
                                                                                       <Button size={"small"}
                                                                                               type={"link"}
                                                                                               onClick={(event) => {
                                                                                                   event.stopPropagation()
                                                                                                   // setEditingDocumentId(item.id) TODO
                                                                                               }}>
                                                                                           <EditOutlined/>
                                                                                       </Button>}
                                                                               </Space>
                                                                           }
                                                                       }
                                                                   ]} dataSource={documents}/>
        </DataPageLayout>
    </>)
})

interface EditMarketAccountSaleDocumentRequest {
    note?: string
    yearAndMonth: Dayjs
}

export default (MarketAccountTabItemPage)
